package com.huawei.esdk.tpoa.tools.cxf.service;

import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.soap.SOAPFaultException;
import com.huawei.esdk.tpoa.tools.cxf.autogen.ArrayOfFilterBase;
import com.huawei.esdk.tpoa.tools.cxf.autogen.ArrayOfSortItem;
import com.huawei.esdk.tpoa.tools.cxf.autogen.Authenticate;
import com.huawei.esdk.tpoa.tools.cxf.autogen.ClientType;
import com.huawei.esdk.tpoa.tools.cxf.autogen.LoginRequest;
import com.huawei.esdk.tpoa.tools.cxf.autogen.LoginRequestResponse;
import com.huawei.esdk.tpoa.tools.cxf.autogen.Logout;
import com.huawei.esdk.tpoa.tools.cxf.autogen.PageParam;
import com.huawei.esdk.tpoa.tools.cxf.autogen.QueryConfig;
import com.huawei.esdk.tpoa.tools.cxf.autogen.QuerySites;
import com.huawei.esdk.tpoa.tools.cxf.autogen.QuerySitesResponse;
import com.huawei.esdk.tpoa.tools.cxf.autogen.SiteParamEx;
import com.huawei.esdk.tpoa.tools.cxf.autogen.SmcExternal2Soap;
import com.huawei.esdk.tpoa.tools.cxf.utils.Base64Utils;
import com.huawei.esdk.tpoa.tools.cxf.utils.ClientProvider;
import com.huawei.esdk.tpoa.tools.cxf.utils.Encrypt;
import com.huawei.esdk.tpoa.tools.cxf.utils.InterfaceOperationType;
import com.huawei.esdk.tpoa.tools.cxf.utils.LoggerMgr;
import com.huawei.esdk.tpoa.tools.cxf.utils.PropertiesUtils;
import com.huawei.esdk.tpoa.tools.cxf.utils.StringUtils;

public class SMCService
{
	
    static
    {
        System.setProperty("org.apache.cxf.JDKBugHacks.defaultUsesCaches", "true");
    }
    
    private SmcExternal2Soap smcExternal2Soap = null;
    
    private static SMCService instance = null;
    
    public static synchronized SMCService getInstance(String url)
    {
        if (null == instance)
        {
            instance = new SMCService(url);
        }
        return instance;
    }
    
    private SMCService(String url)
    {
    	smcExternal2Soap = ClientProvider.getClient(SmcExternal2Soap.class, url);
    }

    public Integer login(String userName, String password)
    {
        LoginRequest loginReq = new LoginRequest();
        loginReq.setClientType(ClientType.API);
        loginReq.setUserName(userName);
        loginReq.setVersion(2);
        LoginRequestResponse loginResp = smcExternal2Soap.loginRequest(loginReq);
        
        LoggerMgr.interfacelogger(InterfaceOperationType.QUERY, 
            "loginRequest",
            loginReq, (int)loginResp.getLoginRequestResult().getErrCode());
        
        if (null != loginResp.getLoginRequestResult() 
        		&& 0 == loginResp.getLoginRequestResult().getErrCode())
        {
            Authenticate authenticate = new Authenticate();
            String encodePwd = Base64Utils.encode(loginResp.getRandomSequence());
            String pwd = Encrypt.getEncryptPassword(null == encodePwd ? "" : encodePwd, password);
            byte[] base64Pwd = Base64Utils.getFromBASE64(null == pwd ? "" : pwd);
            authenticate.setEncryptPassword(null == base64Pwd ? new byte[0] : base64Pwd);
            try
            {
                int authenticateErrcode = (int)smcExternal2Soap.authenticate(authenticate).getAuthenticateResult().getErrCode();
                authenticate.setEncryptPassword(null);
                LoggerMgr.interfacelogger(InterfaceOperationType.QUERY, 
                    "authenticate",
                    authenticate, authenticateErrcode);
                return authenticateErrcode;
            }
            catch (SOAPFaultException e)
            {
                return -1;
            }
        }
        return (int)loginResp.getLoginRequestResult().getErrCode();
    }
    
    public Integer logout()
    {
        try
        {
            int logoutErrCode = (int)smcExternal2Soap.logout(new Logout()).getLogoutResult().getErrCode();
            LoggerMgr.interfacelogger(InterfaceOperationType.QUERY, 
                "logout",
                new Logout(), logoutErrCode);
            return logoutErrCode;
        }
        catch (SOAPFaultException e)
        {
            return -1;
        }
    }
    
    public List<SiteParamEx> querySites()
    {
        List<SiteParamEx> siteList = new ArrayList<SiteParamEx>();
        
        QuerySites south = new QuerySites();
        QueryConfig config = new QueryConfig();
        // �������
        ArrayOfSortItem sortItem = new ArrayOfSortItem();
        config.setSortItems(sortItem);
        // ���˲���
        ArrayOfFilterBase filter = new ArrayOfFilterBase();
        config.setFilters(filter);
        // �������
        config.setFocusItem(0L);
        // ��ҳ���'
        PageParam page = new PageParam();
        page.setCurrentPage(1);

        int numberPerPage = 50; 
        String numberPerPageStr = PropertiesUtils.getValue("numPerPage");
        if(!StringUtils.isEmpty(numberPerPageStr)) 
        {
            try
            {
                numberPerPage = Integer.parseInt(numberPerPageStr);
            }
            catch(NumberFormatException e)
            {
                numberPerPage = 50;
            }
        }
        page.setNumberPerPage(numberPerPage);
        
        config.setPageParam(page);

        south.setQueryConfig(config);
        

        boolean flag = true;
        while(flag)
        {
    
            QuerySitesResponse result = smcExternal2Soap.querySites(south);
            
            LoggerMgr.interfacelogger(InterfaceOperationType.QUERY, 
                "querySites",
                south, (int)result.getQuerySitesResult().getErrCode());
            
            if (null != result && 0 == result.getQuerySitesResult().getErrCode())
            {
                siteList.addAll(result.getSites().getSiteParamEx());

                int curPageNo = result.getPageInfo().getCurrentPage();
                int totalPageCount = result.getPageInfo().getTotalPages();
                if(curPageNo < totalPageCount)
                {
                    south.getQueryConfig().getPageParam().setCurrentPage(curPageNo + 1);
                }
                else
                {
                    flag = false;
                }
            }
            else
            {
                flag = false;
            }
        }
        
        return siteList;
    }
}
